
/**
 * Created by ting.zhang on 2019/11/08 0411.
 */
import React from 'react';
import { connect } from 'react-redux';
import { messages } from 'share/common';
import {Input, InputNumber, Form, Button, Spin, Row, Col, message, DatePicker, Affix, Select} from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
const TextArea = Input.TextArea;

import moment from 'moment';
import travelService from 'containers/request/travel-request/travel.service'
import travelUtil from 'containers/request/travel-request/travelUtil'
import TravelLocation from 'containers/request/travel-request/comp/location'
import TravelPrompt from 'containers/request/travel-request/travel-prompt'
import baseService from "share/base.service";

class TravelCusHotel extends React.Component{
  supply = {};
  searchType = "standard";
  intEnable = true;//是否可选到国际
  clearHistory = false;//是否切换供应商的时候直接清空地址
  startDate = "";
  endDate = "";
  baseStartDate = "";
  baseEndDate = "";
  dateArray = [];//盛放已选过的酒店日期
  out_participant_num = 0;//外部参与人数
  select_participant = [];//参与人
  constructor(props){
    super(props);
    this.state = {
      params:{},//接收父组件带来的参数
      editing:false,//区分编辑页还是新建页
      formCtrl:{},//
      standardEnable:false,//是否走差旅标准
      promptList: [], //行程提示语的配置
      duplicateEnable: false, //是否允许重复的酒店日期
      // supplies: [],//所有供应商
      // currentIndex: 0,//当前供应商数组的下标
      // supplyId:'',//当前供应商serviceName
      defaultDate:""+moment(travelUtil.getDefaultDate(1)).format('YYYY-MM-DD'),
      isLoading: false,//提交是否loading提示
      // citySearchResult:[],//城市搜索结果
      maxRoom:1,//最大房间数
      minPrice:0,//最小价格
      selectCity:{},//选择的住宿城市
      nights:0,//住宿晚间数
      isSelf: false,//酒店类型是否是"自选酒店"
      currencyList: [],//货币列表
    };
  }

  //初始化编辑数据
  componentWillReceiveProps(){
    let cusHotelRecord = [];
    if(this.props.params.isResetCusHotel){
      this.resetForm();
      delete this.props.params.isResetCusHotel;
      return;
    }
    const { editCusHotel, offlinehotel, defaultValue } = this.props.params;
    let editData = travelUtil.isEmpty(editCusHotel);
    let TAG =  editData.isEmpty;
    if(!TAG){
      if(!this.state.editing){
        let num = 0;
        let supId = 0;
        let night = travelUtil.calculateDate(editData.fromDate, editData.leaveDate) - 1;
        this.setState({
          editing:true,
          // currentIndex:num,
          nights:night,
          selectCity:editData.cityName?{code:editData.cityCode,vendorAlias:editData.cityName}:{},
          isSelf: editData.hotelType === 'zx'
        },()=>{
          this.props.form.resetFields();
        })
      }
      offlinehotel.map(h =>{
        if(h.hotelItineraryOID !== editData.hotelItineraryOID){
          cusHotelRecord.push(h);
        }
      });
      this.dateArray = travelUtil.hotelDateArray(cusHotelRecord);
    }else {
      if(offlinehotel){
        this.dateArray = travelUtil.hotelDateArray(offlinehotel);
      };
      let tempStartDate = travelUtil.getFormHeadValue(defaultValue, 'start_date');
      let tempEndDate = travelUtil.getFormHeadValue(defaultValue, 'end_date');
      // let outNum = travelUtil.getFormHeadValue(defaultValue,'out_participant_num');
      let select_participant = [];
      // select_participant = travelUtil.getFormHeadValue(defaultValue,'select_participant');
      if(this.baseStartDate !== tempStartDate || this.baseEndDate !== tempEndDate){//头部时间、参与人、外部参与人数是否已经改变
        this.setThisDate();
      }
    }
    // this.setState({minPrice:this.props.form.getFieldValue('minPrice')});
  }

  componentWillMount(){
    const { params } = this.props;
    // this.getSupplies();
    let tempMap = params['travelInfo']['customFormPropertyMap'];
    let obj = tempMap['application.property.control.fields.offline.hotel'] ? JSON.parse(tempMap['application.property.control.fields.offline.hotel']) : travelUtil.getSetDataByTravelType('offlineHotel');
    let isStandard = tempMap['ca.travel.applypolicy.enable'] ? JSON.parse(tempMap['ca.travel.applypolicy.enable']) : false;
    let promptList = tempMap['travel.itinerary.tips'] ? JSON.parse(tempMap['travel.itinerary.tips']) : [];
    let duplicateEnable = tempMap['hotel.repetition.control'] === 'true';
    // this.updateMaxRoom();
    this.getCurrencyList();//获取货币列表
    this.setThisDate();
    let night = travelUtil.calculateDate(this.baseStartDate, this.baseEndDate) - 1;
    this.setState({
      promptList,
      duplicateEnable,
      params,
      formCtrl:obj,
      standardEnable:isStandard,
      nights:night
    });
  }

  //设置日期
  setThisDate = () =>{
    this.startDate = travelUtil.getFormHeadValue(this.props.params.defaultValue,'start_date');
    this.endDate = travelUtil.getFormHeadValue(this.props.params.defaultValue,'end_date');
    this.baseStartDate = travelUtil.getFormHeadValue(this.props.params.defaultValue,'start_date');
    this.baseEndDate = travelUtil.getFormHeadValue(this.props.params.defaultValue,'end_date');
    // this.out_participant_num = travelUtil.getFormHeadValue(this.props.params.defaultValue,'out_participant_num');
    // this.select_participant = JSON.stringify(travelUtil.getFormHeadValue(this.props.params.defaultValue,'select_participant'));
  }

  //时间改变重新计算日期区间天数
  startDateChange = (e) => {
    const { form } = this.props;
    let endDate = form.getFieldValue('leaveDate');
    this.startDate = e;
    let days = travelUtil.calculateDate(e, endDate);
    this.setState({nights: days - 1});
  }

  //时间改变重新计算日期区间天数
  endDateChange = (e) => {
    const { form } = this.props;
    let startDate = form.getFieldValue('fromDate');
    this.endDate = e;
    let days = travelUtil.calculateDate(startDate, e);
    this.setState({nights: days - 1});
  }

  // updateMaxRoom = () =>{
  //   let outNum = travelUtil.getFormHeadValue(this.props.params.defaultValue,'out_participant_num');
  //   let select_participant = [];
  //   select_participant = travelUtil.getFormHeadValue(this.props.params.defaultValue,'select_participant');
  //   travelService.getMaxRoom(outNum,select_participant).then(res=>{
  //     this.setState({
  //       maxRoom:res.data.maxRoomNumber,
  //     })
  //   }).catch(err=>{
  //     message.error(err.response.data.message);
  //   })
  // }

  getCurrencyList(){
    baseService.getAllCurrencyByLanguage('zh_cn', undefined, true).then(res => {
      this.setState({
        currencyList: res.data
      })
    })
  }

  cfo = travelUtil.createFormOption;

  //清空已选城市数据
  clearCityData = () => {
    this.setState({
      // citySearchResult: [],
      selectCity:{}
    });
    this.props.form.setFieldsValue({cityName: ""});
  };

  //提交
  toSubmit = (e) => {
    const { duplicateEnable, formCtrl, selectCity} = this.state;
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err,values)=>{
      if(values.totalPrice == 0) {
        message.error(messages('my-account.key75'/*金额不能为0*/));
        return;
      }
      if(values.remark && values.remark.length === 201){
        message.error(messages('request.key349'/*备注长度超出*/));
        return;
      }
      if(!err){
        // values.supplierOID = this.supply.supplierOID ? this.supply.supplierOID : null;
        values.fromDate = moment(moment(values.fromDate).format('YYYY-MM-DD')).utc().format();//置为零点零分
        values.leaveDate = moment(moment(values.leaveDate).format('YYYY-MM-DD')).utc().format();//置为零点零分
        if(values.fromDate > values.leaveDate){
          message.error(messages('request.key350'/*退房日期不能小于入住日期*/));
          return;
        }
        if(values.fromDate === values.leaveDate){
          message.error(messages('request.key351'/*退房日期不能等于入住日期*/));
          return;
        }
        if(formCtrl.city && formCtrl.city.required && !selectCity.code){
          message.error(messages('request.key352'/*城市不匹配或未点击选择*/));
          return;
        }
        values.cityCode = selectCity.code?selectCity.code:null;
        values.cityName = selectCity.code?selectCity.vendorAlias:null;
        // values.roomNumber = 1;
        //wjk add 18 05 22 判断是否跨选日期
        let isRepeatDate = travelUtil.hotelIsRepeatDate(values, duplicateEnable ? [] : this.dateArray);
        if(isRepeatDate.isRepeat){
          message.error(messages('request.key469',{arg1: isRepeatDate.dateStr}/*{arg1}已预订*/));
          return;
        }
        this.setState({isLoading:true});
        if(!this.state.editing){
          travelService.travelCusHotelSubmit(this.state.params.oid,[values]).then(res =>{
            this.submitFinish(messages('request.key189'/*已保存*/));
          }).catch(err=>{
            message.error(err.response.data.message);
            this.setState({isLoading:false});
          });
        }else{
          values.applicationOID = this.state.params.oid;
          values.hotelItineraryOID = this.props.params.editCusHotel.hotelItineraryOID;
          travelService.updateCusHotel(values).then(res=>{
            this.submitFinish(messages('request.key353'/*已更新*/))
          }).catch(err=>{
            message.error(err.response.data.message);
            this.setState({isLoading:false});
          })
        }
      }
    })
  }

  //提交成功提示
  submitFinish = (mes) =>{
    this.setState({isLoading:false});
    message.success(mes);
    this.props.form.resetFields();
    this.closeSlide();
  }

  //获取供应商数据
  // getSupplies = () =>{
  //   travelService.travelSuppliers(2003).then(res=>{
  //     if(res['data']['2003']){
  //       let defaultIndex = 0;
  //       res['data']['2003'].map((item, index) => {
  //         if (item.userDefault) {
  //           defaultIndex = index;
  //         }
  //       });
  //       this.setState({
  //         supplies:res['data']['2003'],
  //         supplyId:res['data']['2003'].length > 0 ? res['data']['2003'][defaultIndex].serviceName : "",
  //         currentIndex: defaultIndex
  //       },() => {
  //         this.supply = this.state.supplies.length > 0 ? this.state.supplies[defaultIndex] : {};
  //         if (this.supply.function && this.supply.function[0]) {
  //           this.searchType = this.supply.function[0].locationVendorType;
  //           this.intEnable = this.supply.function[0].intEnable;
  //         }
  //       });
  //     }
  //   }).catch(err=>{
  //     message.error(err.response.data.message);
  //   });
  // }

  //重置表单
  resetForm = () =>{
    this.props.form.resetFields();
    delete this.props.params.editCusHotel;
    let night = travelUtil.calculateDate(this.baseStartDate, this.baseEndDate) - 1;
    this.setThisDate();
    this.setState({
      editing:false,
      nights:night,
      isSelf: false
    });
  }

  // 关闭侧滑
  closeSlide = () =>{
    this.props.close();
  };

  selectCity = (cityObj) =>{
    this.setState({selectCity: cityObj});
  };

  disabledDateStart = (current) => {
    const { duplicateEnable, formCtrl } = this.state;
    // const floatLeaveDay = formCtrl.leaveDate.floatDays;
    // const floatStartDay = -formCtrl.fromDate.floatDays;
    const floatLeaveDay = 0;
    const floatStartDay = 0;
    return travelUtil.disabledDate(current, this.baseStartDate, this.baseEndDate, floatLeaveDay, floatStartDay, duplicateEnable ? undefined : this.dateArray) ;
  };

  disabledDateEnd = (current) => {
    const { duplicateEnable, formCtrl } = this.state;
    // const floatLeaveDay = formCtrl.leaveDate.floatDays + 1;
    // const floatStartDay = -formCtrl.fromDate.floatDays + 1;
    const floatLeaveDay = 1;
    const floatStartDay = 1;
    return travelUtil.disabledDate(current, this.baseStartDate, this.baseEndDate, floatLeaveDay, floatStartDay, duplicateEnable ? undefined : this.dateArray) ;
  };

  //交通类型选择
  hotelTypeHandle = (value) => {
    console.log(value);
    const isSelf = value === 'zx';
    this.setState({isSelf});
    !isSelf && this.props.form.setFieldsValue({optionalReason: ''});
  };

  //城市选择
  selectCity = (cityObj) =>{
    this.setState({selectCity: cityObj});
  };

  render(){
    const {formCtrl, maxRoom, minPrice, standardEnable, supplies, defaultDate, supplyId, currentIndex, isLoading,
      citySearchResult, nights, promptList, isSelf, currencyList} = this.state;
    const {getFieldDecorator} = this.props.form;
    const {travelInfo: {formCode}} = this.props.params;
    let editData = travelUtil.isEmpty(this.props.params.editCusHotel);
    const { isEmpty, hotelName, cityName, star = '01', roomType, hotelType = 'dhzd', optionalReason, totalPrice, remark } = editData;
    let currency = editData.currency || this.props.company.baseCurrency;
    const TAG =  editData.isEmpty;
    const formSupplyLayout = {
      labelCol: {span: 4},
      wrapperCol: {span: 18}
    };
    const formLayout = {
      labelCol: {span: 8},
      wrapperCol: {span: 12}
    };
    const fc_city = formCtrl.city || {};
    const fc_hotelName = formCtrl.hotelName || {};
    const fc_star = formCtrl.star || {};
    const fc_roomType = formCtrl.roomType || {};
    const fc_hotelType = formCtrl.hotelType || {};
    const fc_optReason = formCtrl.optionalReason || {};
    const fc_fromDate = formCtrl.fromDate || {};
    const fc_leaveDate = formCtrl.leaveDate || {};
    const fc_ccy = formCtrl.currency || {};
    const fc_totalPrice = formCtrl.totalPrice || {};
    const fc_remark = formCtrl.remark || {};
    return (
      <div className="travel-hotel">
        <TravelPrompt promptList={promptList} type={1011} />
        <Spin spinning={isLoading}>
          <Form>
            <Row>
              {
                fc_city && (fc_city.enable || fc_city.show) &&  <Col span={12}>
                  <FormItem {...formLayout} label={messages('request.key357'/*入住城市*/)}>
                    {getFieldDecorator('cityName',this.cfo(messages('request.key357'/*入住城市*/),{type:'str',value:cityName},!fc_city.required))(
                      <TravelLocation isEntity={false}
                                      formCode={formCode}
                                      onSelect={this.selectCity}
                                      isOldDataType={true}/>
                    )}
                  </FormItem>
                </Col>
              }
              {
                fc_hotelName && (fc_hotelName.enable || fc_hotelName.show) && <Col span={12}>
                  <FormItem  {...formLayout} label={messages('financial-management.key728'/*酒店名称*/)}>
                    {getFieldDecorator('hotelName',this.cfo(messages('financial-management.key728'/*酒店名称*/),{type:'str',value:hotelName||''}, !fc_hotelName.required))
                    (<Input placeholder={messages('common.please.input')/*请输入*/}/>)}
                  </FormItem>
                </Col>
              }
            </Row>

            <Row>
              {
                fc_star && (fc_star.enable || fc_star.show) && <Col span={12}>
                  <FormItem {...formLayout} label={messages('financial-management.key729'/*星级*/)}>
                    {getFieldDecorator('star',this.cfo(messages('financial-management.key729'/*星级*/),{type:'str',value:star||''}, !fc_star.required))(
                      <Select>
                        <Option value="01">{messages('mcd.custom.hotel.star.level1'/*三星及以下*/)}</Option>
                        <Option value="02">{messages('mcd.custom.hotel.star.level2'/*四星级*/)}</Option>
                        <Option value="03">{messages('mcd.custom.hotel.star.level3'/*五星及以上*/)}</Option>
                      </Select>
                    )}
                  </FormItem>
                </Col>
              }
              {
                fc_roomType && (fc_roomType.enable || fc_roomType.show) && <Col span={12}>
                  <FormItem  {...formLayout} label={messages('mcd.room.type'/*房型*/)}>
                    {getFieldDecorator('roomType',this.cfo(messages('mcd.room.type'/*房型*/),{type:'str',value:roomType||''}, !fc_roomType.required))
                    (<Input placeholder={messages('common.please.input')/*请输入*/}/>)}
                  </FormItem>
                </Col>
              }
            </Row>

            <Row>
              {
                fc_hotelType && (fc_hotelType.enable || fc_hotelType.show) && <Col span={12}>
                  <FormItem {...formLayout} label={messages('mcd.hotel.type'/*酒店类型*/)}>
                    {getFieldDecorator('hotelType',this.cfo(messages('mcd.hotel.type'/*酒店类型*/),{type:'str',value:hotelType}, !fc_hotelType.required))(
                      <Select onChange={this.hotelTypeHandle}>
                        <Option value="dhzd">{messages('mcd.dhzd'/*大会指定酒店*/)}</Option>
                        <Option value="zx">{messages('mcd.zx'/*自选酒店*/)}</Option>
                      </Select>
                    )}
                  </FormItem>
                </Col>
              }
              {
                isSelf && <Col span={24}>
                  <FormItem  {...formSupplyLayout} label={messages('mcd.self.reason'/*自选酒店理由*/)}>
                    {getFieldDecorator('optionalReason',this.cfo(messages('mcd.self.reason'/*自选酒店理由*/),{type:'str',value:optionalReason||'', maxNum: 1000}, false))
                    (<TextArea placeholder={messages('common.please.input')/*请输入*/}/>)}
                  </FormItem>
                </Col>
              }
            </Row>

            <Row>
              {
                fc_fromDate && (fc_fromDate.enable || fc_fromDate.show) && <Col span={12}>
                  <FormItem {...formLayout} label={messages('request.key360'/*入住日期*/)}>
                    {getFieldDecorator('fromDate',this.cfo(messages('request.key360'/*入住日期*/),{type:'moment',value:isEmpty?this.baseStartDate:editData.fromDate}, !fc_fromDate.required))(
                      <DatePicker onChange={this.startDateChange} disabledDate={this.disabledDateStart}></DatePicker>
                    )}
                  </FormItem>
                </Col>
              }
              {
                fc_leaveDate && (fc_leaveDate.enable || fc_leaveDate.show) &&
                <div className="night">{messages('request.key470', {arg1: nights}/*{arg1}晚*/)}</div>
              }
              {
                fc_leaveDate && (fc_leaveDate.enable || fc_leaveDate.show) &&  <Col span={12}>
                  <FormItem {...formLayout} label={messages('request.key361'/*退房日期*/)}>
                    {getFieldDecorator('leaveDate',this.cfo(messages('request.key361'/*退房日期*/),{type:'moment',value:isEmpty?this.baseEndDate:editData.leaveDate}, !fc_leaveDate.required))(
                      <DatePicker onChange={this.endDateChange} disabledDate={this.disabledDateEnd}></DatePicker>
                    )}
                  </FormItem>
                </Col>
              }
            </Row>
            {
              <Row>
                <Col span={12}>
                  <FormItem {...formLayout} label={messages('mcd.custom.hotel.order.amt'/*含税总金额*/)} required={fc_totalPrice.required}>
                    <Col span={12}>
                      <FormItem>
                        {getFieldDecorator('currency',this.cfo(messages('common.currency'/*币种*/),{type:'str',value:currency}, !fc_totalPrice.required))(
                          <Select className="for-offline-amt"
                                  optionLabelProp="label"
                                  getPopupContainer={() => document.getElementsByClassName('for-offline-amt')[0]}>
                            {
                              currencyList.length>0 && currencyList.map(item => {
                                return <Option key={item.currency} label={item.currency}>{item.currency}{this.props.language.code === 'zh_cn' ? ` ${item.currencyName}` : ''}</Option>
                              })
                            }
                          </Select>
                        )}
                      </FormItem>
                    </Col>

                    <Col span={11} offset={1}>
                      <FormItem>
                        {getFieldDecorator('totalPrice',this.cfo(messages('common.amount'/*金额*/),{type:'number',value:totalPrice}, !fc_totalPrice.required))(
                          <InputNumber className="maxPrice" min={0}/>
                        )}
                      </FormItem>
                    </Col>
                  </FormItem>
                </Col>
              </Row>
            }

            {
              fc_remark && (fc_remark.enable || fc_remark.show) &&
              <FormItem label={messages('request.key364'/*备注*/)} {...formSupplyLayout}>
                {getFieldDecorator('remark', {
                  rules: [{
                    required: fc_remark.required,
                    message: messages('request.key472', {arg1: messages('request.key364'/*备注*/)}/*{arg1}不能为空*/)
                  }],
                  initialValue: remark
                })(
                  <TextArea maxLength="200" placeholder={messages('request.key372'/*请输入*/)}/>
                )}
              </FormItem>
            }
          </Form>
        </Spin>
        <Affix className="travel-affix" offsetBottom={0}>
          <Button onClick={this.toSubmit} type="primary" loading={isLoading}>{messages('request.key211'/*确定*/)}</Button>
          <Button className="travel-type-btn" onClick={this.closeSlide} >{messages('request.key175'/*取消*/)}</Button>
        </Affix>
      </div>
    )
  }



}

function mapStateToProps(state) {
  return {
    company: state.login.company,
    language: state.main.language
  };
}

const wrappedTravelHotel = Form.create()(TravelCusHotel);

export default connect(mapStateToProps)(wrappedTravelHotel);
